import { getSetting, chooseAddress, openSetting, showModal, showToast, requestPayment } from "../../utils/asyncWx.js"
import regeneratorRuntime from '../../lib/runtime/runtime'
import { request } from "../../request/index.js"

// pages/cart/index.js
Page({
  data: {
    // 用户地址
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0,

  },
  onShow() {
    // 1. 获取缓存中的收获地址信息
    let address = wx.getStorageSync("address");
    // 1. 获取缓存中的购物车数据
    let cart = wx.getStorageSync("cart") || [];
    cart = cart.filter(v => v.checked)
    this.setData({
      address
    })
    // 1. 总价格 总数量
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      totalPrice += v.num * v.goods_price;
      totalNum += v.num
    })

    this.setData({
      cart,
      totalPrice,
      totalNum,

    })
  },
  // 点击结算
  async handleOrderPay() {
    try {
      // 1. 判断缓存中有没有 token 值
      let token = wx.getStorageSync("token");
      if (!token) {
        wx.navigateTo({
          url: '/pages/auth/index'
        })
        return;
      }
      // 创建订单
      // 准备请求头参数
      let header = { Authorization: token };
      // 准备请求体参数
      let order_price = this.data.totalPrice;
      let consignee_addr = this.data.address.all;
      let cart = this.data.cart;
      let goods = [];
      cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.goods_price
      }))
      // 准备发送请求，创建订单，获取订单编号
      let orderParams = { order_price, consignee_addr, goods };
      let { order_number } = await request({ url: "/my/orders/create", method: "POST", data: orderParams, header })
      // 发起预支付接口
      let { pay } = await request({ url: "/my/orders/req_unifiedorder", method: "POST", data: { order_number }, header })
      // console.log(pay)
      // 发起微信支付
      let { res } = await requestPayment(pay);
      console.log(res)
    } catch (err) {
      console.log(err);
    }

  }
})